package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import VideoHandle.EpAudio;
import VideoHandle.EpEditor;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.AudioMergerAdapter;
import flc.ast.databinding.ActivityAudioSpliceBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.constant.Extra;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.WorkPathUtil;

public class AudioSpliceActivity extends BaseAc<ActivityAudioSpliceBinding> {

    private AudioMergerAdapter mAudioMergeAdapter;
    private String mMergePath;
    private AudioPlayerImpl mAudioPlayer;
    private AudioPlayerImpl mCurAudioPlayer;
    private static final int REQ_AUDIO = 1;
    public static List<String> mAddList = new ArrayList<>();
    private String mResultPath;
    private String mAudioName;

//    public static void start(Context context, String audioPath) {
//        Intent intent = IntentUtil.getIntent(context, AudioSpliceActivity.class);
//        intent.putExtra(Extra.PATH, audioPath);
//        context.startActivity(intent);
//    }

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_splice;
    }

    @Override
    protected void initView() {

        mDataBinding.ivAudioSpliceBack.setOnClickListener(v -> onBackPressed());

//        mMergePath = getIntent().getStringExtra(Extra.PATH);
//        mResultPath = mMergePath;
//        mAddList.add(mMergePath);
        mAudioPlayer = new AudioPlayerImpl();
        mCurAudioPlayer = new AudioPlayerImpl();
        mCurAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(curPlayTime));
                mDataBinding.tvPlayRightText.setText("/" + TimeUtil.getMmss(duration));
                mDataBinding.trackView.setPlayTime(curPlayTime);
                mDataBinding.trackView.setDuration(duration);
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.abofzhong);
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.azantinz);
                }
            }
        });

//        mAudioName = FileUtils.getFileName(mResultPath);


        mAudioMergeAdapter = new AudioMergerAdapter(mAudioPlayer);
        mAudioMergeAdapter.setListener(new AudioMergerAdapter.Ilistener() {
            @Override
            public void clickDelete(int position) {
                mAddList.remove(position);
                clickAddMerger();
            }
        });
        mAudioMergeAdapter.mCurAudioPlayer = mCurAudioPlayer;
        mDataBinding.lvAudio.setAdapter(mAudioMergeAdapter);
        for (String s : mAddList) {
            mAudioMergeAdapter.addAudioPath(s);
        }
        mDataBinding.llAdd.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivAudioSpliceSave.setOnClickListener(this);

    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlay://播放
//                if (mAudioMergeAdapter.getCount() > 1) {
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                }
                if (mCurAudioPlayer.isPlaying()) {
                    mCurAudioPlayer.pause();
                } else {
                    mCurAudioPlayer.resume();
                }
//                } else {
//                    ToastUtils.showShort(R.string.least_two_tips);
//                }
                break;
            case R.id.ivAudioSpliceSave://保存
                if (mAudioMergeAdapter.getCount() > 1) {
                    save();
                } else {
                    ToastUtils.showShort(R.string.please_add_audio_file_hint);
                }
                break;
            case R.id.llAdd://添加视频
                Intent intent = new Intent(AudioSpliceActivity.this, SelAudioActivity.class);
                intent.putExtra(Content.AgainAudio, "Again");
                startActivityForResult(intent, REQ_AUDIO);
                break;
        }
    }

    @Override
    protected void initData() {
        clickAddMerger();
    }

    private void save() {
        //音频拼接
        List<EpAudio> audioList = new ArrayList<>();
        for (int i = 0; i < mAudioMergeAdapter.getCount(); i++) {
            audioList.add(createEpAudio(mAudioMergeAdapter.getHolderList().get(i)));
        }
        mAudioName = FileUtils.getFileName(mResultPath);
        String path = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + mAudioName;
        showDialog(getString(R.string.saving));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                EpEditor.audioConcat(audioList, path, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        emitter.onNext(path);
                    }

                    @Override
                    public void onFailure() {
                        dismissDialog();
                    }

                    @Override
                    public void onProgress(float progress) {
                    }
                });
            }

            @Override
            public void accept(String audioOutPath) {
                if (!TextUtils.isEmpty(audioOutPath)) {
                    mDataBinding.ivAudioSpliceSave.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dismissDialog();
                            FileP2pUtil.copyPrivateAudioToPublic(mContext, audioOutPath);
                            ToastUtils.showShort(getString(R.string.save_success));
                            startActivity(HomeActivity.class);
                        }
                    }, 1000);
                }
            }
        });
    }


    private void clickAddMerger() {
        showDialog(getString(R.string.audio_splice_tips));
        //音频拼接
        List<EpAudio> audioList = new ArrayList<>();
        for (int i = 0; i < mAddList.size(); i++) {
            audioList.add(new EpAudio(mAddList.get(i)));
        }
//        ToastUtils.showShort(mAddList.size());
        String audioOutPath = FileUtil.generateFilePath(Content.myTemp, ".mp3");
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                EpEditor.audioConcat(audioList, audioOutPath, new OnEditorListener() {
                    @Override
                    public void onSuccess() {
                        emitter.onNext(audioOutPath);
                    }

                    @Override
                    public void onFailure() {
                        dismissDialog();
                    }

                    @Override
                    public void onProgress(float progress) {
                    }
                });
            }

            @Override
            public void accept(String audioOutPath) {
                if (!TextUtils.isEmpty(audioOutPath)) {
                    dismissDialog();
                    if (mAudioPlayer.isPlaying()) {
                        mAudioPlayer.pause();
                    }
                    mResultPath = audioOutPath;
                    mCurAudioPlayer.play(mResultPath);
                }
            }
        });
    }

    protected EpAudio createEpAudio(@NonNull AudioMergerAdapter.ViewHolder holder) {
        EpAudio epAudio = new EpAudio(holder.mBindPath);
        float startTime = holder.mTrackView.getStartTime() / 1000f;
        float duration = holder.mTrackView.getEndTime() / 1000f - startTime;
        if (duration < 0) {
            duration = 0;
        }
        epAudio.clip(startTime, duration);
        return epAudio;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }

        if (mCurAudioPlayer != null) {
            mCurAudioPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
        if (mCurAudioPlayer != null) {
            mCurAudioPlayer.stop();
        }
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
        FileUtils.deleteAllInDir(PathUtils.getFilesPathExternalFirst() + WorkPathUtil.WORK_AUDIO_DIR);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_AUDIO) {
            if (resultCode != Activity.RESULT_OK) {
                return;
            }
            String path = data.getStringExtra(Content.audioPath);
            if (!TextUtils.isEmpty(path)) {
//                if (mAudioMergeAdapter.getCount() < 6) {
                mAddList.add(path);
                mAudioMergeAdapter.addAudioPath(path);
                clickAddMerger();
//                } else {
//                    ToastUtils.showShort(R.string.max_mix_6_text);
//                }
            }

        }
    }


}